package com.lanou3g.Code0523.dynamic;

import com.lanou3g.Code0523.permission.BaseFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.File;
import java.io.IOException;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/5/23;
 * Otherwise, I don't know who created it either
 */

@WebFilter(filterName = "RandomFilter",servletNames = "RandomServlet")
public class RandomFilter extends BaseFilter {
    @Override
    public void doFilter(HttpServletRequest request,
                         HttpServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        // 思路
        // 当第一次访问 资源的时候,根据servlet输出的结果
        // 生成一个html的文件
        // 之后 只要这个html文件存在,那么就不去访问servlet了
        // 而是直接把这个html返回

        // 动态页面静态化,其实就是缓存
        // 真正会用redis做

        ServletContext app = request.getServletContext();
        String filePath
                 = app.getRealPath("")
                + File.separator + "random.html";
        File file = new File(filePath);

        if (!file.exists()){
            // 生成html文件
            MyResponse myResponse
                    = new MyResponse(response,
                    request.getServletContext());

            chain.doFilter(request,myResponse);
            myResponse.writeFile();
        }
        // 请求转发
        request.getRequestDispatcher("/random.html")
                .forward(request,response);



    }
}
